/*
 * Carlos René Michel Morales
 * 
 * Clase para realizar la conexiones HTTP
 */

package piticli.twitter;

import java.net.*;
import java.io.*;
import sun.misc.BASE64Encoder;
/**
 *
 * @author Rene
 */
public class Connection {

    String plainText;
    private int responseCode;
    
    /**
     * 
     * @param url Un string que contiene la direccion URL
     * @return un String que contiene el texto plano que regreso el servidor
     */
    public String getPlainText(String url)
    {
        try {
         URL site = new URL(url);
         URLConnection siteConnection = site.openConnection();
         DataInputStream dis = new DataInputStream(siteConnection.getInputStream());
         String inputLine;
         while ((inputLine = dis.readLine()) != null) {
                plainText += inputLine;
            }
         dis.close();
      }
      catch (MalformedURLException me) {
        System.out.println("MalformedURLException: " + me);
      }
      catch (IOException ioe) {
         System.out.println("IOException: " + ioe);
      }
        
        return plainText;
    }
    
    public String urlPOST(String data, String url)
    {
        try {
            // Construct data
            //String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
            //data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

            // Send data
            URL site = new URL(url);
            URLConnection conn = site.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                plainText += line;
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
        }
        
        return plainText;
    }
    
    public String postWithBasicAuthConnection(String username, String password, String url_string, String data) throws Exception
    {
        URL url = new URL( url_string );
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        // Se fija la conexión url para sacar la informacion
        //con.setRequestMethod( "POST" );
        con.setDoInput( true );
        con.setDoOutput(true);
        
        // se llama el request header con las credenciales
        byte[] encodedPassword = ( username + ":" + password ).getBytes();
        BASE64Encoder encoder = new BASE64Encoder();
        con.setRequestProperty( "Authorization",
                                "Basic " + encoder.encode( encodedPassword ) );
        
        //Se hace el POST
        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
        wr.write(data);
        wr.flush();

        // se obtiene la info del url
        InputStream is = con.getInputStream();
        StringBuffer buf = new StringBuffer();
        int c;
        while( ( c = is.read() ) != -1 ) {
          buf.append( (char) c );
        }
        
        this.responseCode = con.getResponseCode();
        con.disconnect();

        // regresamos la respuesta en String
        return buf.toString();
    }
    
    public String basicAuthConnection(String username, String password, String url_string) throws Exception
    {
         URL url = new URL( url_string );
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        // Se fija la conexión url para sacar la informacion
        con.setRequestMethod( "GET" );
        con.setDoInput( true );

        // se llama el request header con las credenciales
        byte[] encodedPassword = ( username + ":" + password ).getBytes();
        BASE64Encoder encoder = new BASE64Encoder();
        con.setRequestProperty( "Authorization",
                                "Basic " + encoder.encode( encodedPassword ) );

        // se obtiene la info del url
        InputStream is = con.getInputStream();
        StringBuffer buf = new StringBuffer();
        int c;
        while( ( c = is.read() ) != -1 ) {
          buf.append( (char) c );
        }
        
        this.responseCode = con.getResponseCode();
        con.disconnect();

        // regresamos la respuesta en String
        return buf.toString();
    }

    public int getResponseCode() {
        return responseCode;
    }
}
